package Worm;

import java.util.LinkedList;

public class Worm {
	private LinkedList<Node> nodes = new LinkedList<Node>();
	private int dir;
	//分为四个固定的方向
	public final static int UP = -10;
	public static final int DOWN = 10;
	public static final int LEFT = -1;
	public static final int RIGHT = 1;
	
	//按照文档图来写的初始化
	public Worm(){
		nodes.add(new Node(3,9));
		nodes.add(new Node(4,9));
		nodes.add(new Node(5,9));
		nodes.add(new Node(5,10));
		nodes.add(new Node(5,11));
		nodes.add(new Node(6,11));
		nodes.add(new Node(7,11));
		this.dir=UP;
	}
	//传递linkedlist<node>()
	public Worm(LinkedList<Node> nodes){
		this.nodes.clear();
		//把传递过来的nodes给this.nodes
		this.nodes.addAll(nodes);
	}
	
	public void step(){
		// 取得原来的坐标head
		Node head = this.nodes.getFirst();
		int i = head.getI()+dir/10;
		int j = head.getJ()+dir%10;
		//创建移动后的头的坐标
		Node head1 = new Node(i,j);
		//加头
		this.nodes.addFirst(head1);
		//去尾
		this.nodes.removeLast();
		System.out.println(this.nodes.toString());
	}
	
	public void step(int dir){
		//换方向
		//相反方向的移动，用RuntimeException:运行期异常,程序正在运行，突然出现错误，突然终止程序
		if(this.dir+dir==0){
			throw new RuntimeException("方向错误");
		}
		this.dir=dir;
		step();
	}
	
	public boolean contains(Node node){
		return this.nodes.contains(node);
	}
	
}
